package com.mashibing.tank.net;

import com.mashibing.tank.GameModel;
import com.mashibing.tank.TankFrame;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ReferenceCountUtil;

/**
 * @description:
 * @author: 余希瑶
 * @date: 2021年06月25日 14:28
 * @version:1.0
 */
public class Client {

    public static final Client INSTANCE = new Client();


    private Channel channel = null;

    public Client(){}

    public  void connect()  {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(1);

        Bootstrap b = new Bootstrap();
       try {
           b.group(workerGroup);
           b.channel(NioSocketChannel.class);

           b.handler(new ChannelInitializer<SocketChannel>() {
               @Override
               protected void initChannel(SocketChannel socketChannel) throws Exception {
                   channel = socketChannel;
                   socketChannel.pipeline()
                           .addLast(new MsgEncoder())
                           .addLast(new MsgDecoder())
                           .addLast(new MyHandler());
               }
           });

           ChannelFuture future = b.connect("localhost", 8888).sync();
           System.out.println("connected to server");

           //等待关闭
           future.channel().closeFuture().sync();

           System.out.println("go on");
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           workerGroup.shutdownGracefully();
       }

    }

    public void send(String text) {
        channel.writeAndFlush(Unpooled.copiedBuffer(text.getBytes()));
    }

    public void closeConnection() {
        send("--byte--");
        channel.close();
    }

    static class  MyHandler extends SimpleChannelInboundHandler<TankJoinMsg> {
       /* @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = null;
            try {

                buf =(ByteBuf)msg;
                byte [] bytes =new byte[buf.readableBytes()];
                buf.getBytes(buf.readerIndex(),bytes);
                String str = new String(bytes);
                //ClientFrame.INSTANCE.updateText(str);


                //super.channelRead(ctx, msg);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(buf != null){
                    ReferenceCountUtil.release(buf);
                }

            }
        }*/

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TankJoinMsg msg) throws Exception {
            System.out.println(msg);
            msg.handle();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(new TankJoinMsg(TankFrame.INSTANCE.getGm().getMyTank()));

            //TankMsg tankMsg = new TankMsg(1, 22);

            //ByteBuf buf = Unpooled.copiedBuffer("mashibing".getBytes());
            //ctx.writeAndFlush(tankMsg);
        }
    }

    public static void main(String[] args) {
        Client c = new Client();
        c.connect();
    }
}
